import axios from 'axios'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import vue from 'vue'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import { tansParams, blobValidate } from '@/utils/ruoyi'
let downloadLoadingInstance

const request = function (loadtip, query) {
  let loading
  if (loadtip) {
    loading = vue.prototype.$loading({
      lock: false,
      text: '正在加载中…',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.5)'
    })
  }
  return axios.request(query)
    .then(res => {
      if (loadtip) {
        loading.close()
      }
      if (res.data.code === 401) {
        vue.prototype.$$router.push({ path: '/login' })
        return Promise.reject(res.data)
      }/* else if (res.data.code === 500) {
        // return Promise.reject(res.data)
        return Promise.resolve(res.data)
      } else if (res.data.code === 501) {
        // return Promise.reject(res.data)
        return Promise.resolve(res.data)
      } else if (res.data.code === 502) {
        vue.prototype.$$router.push({ path: '/login' })
        return Promise.reject(res.data)
      } */else {
        return Promise.resolve(res.data)
      }
    })
    .catch(e => {
      if (loadtip) {
        loading.close()
      }
      // vue.prototype.$message.error(e.message)
      return Promise.reject(e.message)
    })
}

const post = function (url, params) {
  const query = {
    baseURL: process.env.VUE_APP_URL,
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 30000,
    data: params,
    headers: { 'Content-Type': 'application/json', 'request-ajax': true, isToken: true }
  }
  return request(false, query)
}

const postWithLoadTip = function (url, params) {
  const query = {
    baseURL: process.env.VUE_APP_URL,
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 30000,
    data: params,
    headers: { 'Content-Type': 'application/json', 'request-ajax': true }
  }
  return request(true, query)
}

const postWithOutLoadTip = function (url, params) {
  const query = {
    baseURL: process.env.VUE_APP_URL,
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 30000,
    data: params,
    headers: { 'Content-Type': 'application/json', 'request-ajax': true }
  }
  return request(false, query)
}

const get = function (url, params) {
  const query = {
    baseURL: process.env.VUE_APP_URL,
    url: url,
    method: 'get',
    withCredentials: true,
    timeout: 30000,
    params: params,
    headers: { 'request-ajax': true }
  }
  return request(false, query)
}

const form = function (url, params) {
  const query = {
    baseURL: process.env.VUE_APP_URL,
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 30000,
    data: params,
    headers: { 'Content-Type': 'multipart/form-data', 'request-ajax': true }
  }
  return request(false, query)
}

const downloadDoc = async function (url, params) {
  const docEmpNm = params.docEmpNm
  const docDeptNm = params.docDeptNm
  let mm = new Date().getMonth() + 1
  if (mm.length < 2) {
    mm = '0' + mm
  }
  let dd = new Date().getDate()
  if (dd.length < 2) {
    dd = '0' + dd
  }
  const nowTm = new Date().getFullYear().toString() + mm + dd + ' ' + new Date().getHours().toString() + ':' + new Date().getMinutes().toString() + ':' + new Date().getSeconds().toString()
  downloadLoadingInstance = Loading.service({ text: '正在导出，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' })
  const query = {
    baseURL: process.env.VUE_APP_URL,
    url: url,
    method: 'get',
    withCredentials: true,
    responseType: 'blob',
    timeout: 30000,
    params: params,
    headers: {
      isToken: true,
      'request-ajax': true,
      'Authorization': 'Bearer ' + getToken(),
      'Content-Type': 'application/json'
    },
  }
  try {
    const res = await request(false, query)
    console.log('res:', res)
    let blob = new Blob([res], { type: "application/msword" }), // 此处为生成doc
      link = document.createElement("a"), href = window.URL.createObjectURL(blob)
    link.href = href
    link.download = 'YXYYPF-YP-QR-' + docDeptNm + '-' + docEmpNm + '个人教育培训档案--' + nowTm + '.docx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(href) // 释放掉blob对象

    downloadLoadingInstance.close()
  } catch (r) {
    console.error(r)
    Message.error('导出文件出现错误，请联系管理员！')
    downloadLoadingInstance.close()
  }
}

const downloadExcel = async function (url, params) {
  // const docEmpNm = params.docEmpNm
  // const docDeptNm = params.docDeptNm
  const type = params.type
  let mm = new Date().getMonth() + 1
  if (mm.length < 2) {
    mm = '0' + mm
  }
  let dd = new Date().getDate()
  if (dd.length < 2) {
    dd = '0' + dd
  }
  const nowTm = new Date().getFullYear().toString() + mm + dd + ' ' + new Date().getHours().toString() + ':' + new Date().getMinutes().toString() + ':' + new Date().getSeconds().toString()
  downloadLoadingInstance = Loading.service({ text: '正在导出，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' })
  const query = {
    baseURL: process.env.VUE_APP_URL,
    url: url,
    method: 'post',
    withCredentials: true,
    responseType: 'blob',
    timeout: 30000,
    data: params,
    headers: {
      isToken: true,
      'request-ajax': true,
      'Authorization': 'Bearer ' + getToken(),
      'Content-Type': 'application/json'
    },
  }
  try {
    const res = await request(false, query)
    console.log('res:', res)

    let blob = new Blob([res], 
      { type:'application/vnd.ms-excel;charset=utf-8;' }
    ); 

      const link = document.createElement("a");  //创建a标签
      let fliaName =  'YXYYPF-YP-QR-' + '答卷列表--' + nowTm + '.xlsx'
      if (type == 1) {
        fliaName = 'YXYYPF-YP-QR-' + '批改列表--' + nowTm + '.xlsx'
      } else {
        fliaName = 'YXYYPF-YP-QR-' + '试卷完成列表--' + nowTm + '.xlsx'
      }
      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      link.download = fliaName;  //导出文件名
      document.body.appendChild(link);
      link.click();//执行下载
      URL.revokeObjectURL(link.href);  //释放url
      document.body.removeChild(link);  //释放标签

    downloadLoadingInstance.close()
  } catch (r) {
    console.error(r)
    Message.error('导出文件出现错误，请联系管理员！')
    downloadLoadingInstance.close()
  }
}

export {
  post,
  postWithLoadTip,
  postWithOutLoadTip,
  get,
  form,
  downloadDoc,
  downloadExcel
}


